package blogsys.demo.config;

import blogsys.demo.utils.JsonResult;
import blogsys.demo.utils.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static blogsys.demo.utils.ResultCode.USER_FAIL_TOKEN_CHECK;
import static blogsys.demo.utils.ResultCode.USER_NOT_LOGIN;

/**
 * token拦截器 从请求头中获取token 没有token或解析失败 不允许放行
 */
public class JwtTokenHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("text/json;charset=utf-8");

        String token = request.getParameter("token");
        if(token==null){
            //未登录
            JsonResult result = new JsonResult(false, USER_NOT_LOGIN);
            response.getWriter().print(result);
            return false;
        }
        if(JwtUtils.checkToken(request)){
            //解析失败
            JsonResult result = new JsonResult(false, USER_FAIL_TOKEN_CHECK);
            response.getWriter().print(result);
            return false;
        }
        return true;
    }
}
